package net.example.db;

import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

import net.example.manager.ClientGlobalCache;
import net.example.model.common.ChatBoxElemnetType;
import net.example.model.common.NonText;
import net.example.model.common.RichChatMessage;
import net.example.activity.view.sessionview.MessageItem;

import java.util.ArrayList;
import java.util.Date;
import java.util.Map;

/**
 * Created by ZN on 2016/1/11.
 */
public class LastChatRecordPersister {


    private static LastChatRecordPersister instance = new LastChatRecordPersister();
    private LastChatRecordPersister(){}

    public static LastChatRecordPersister getInstance() {
        return instance;
    }

    public void addOrUpdate(MessageItem item) {
        if (existSender(item.senderID)) {
            this.update(item);
            return;
        }
        SQLiteDatabase db = DatabaseHelper.getInstance().getWritableDatabase();
        ContentValues values = new ContentValues();
        values.put("SenderID", item.senderID);
//        values.put("IconRes", item.iconRes);
        values.put("Title", item.title);
        values.put("LastWord", item.lastWord);
        values.put("UnReadCount", item.unReadCount);
        if(item.time==null) {
            item.time=new Date();
        }
        values.put("Time", item.time.getTime());
        values.put("IsGroup", item.isGroup);
        //调用方法插入数据
        db.insert(DatabaseHelper.LastChatRecord, "Title", values);
        db.close();
    }

    public ArrayList<MessageItem> getMyLastMessageRecord() {
        SQLiteDatabase db = DatabaseHelper.getInstance().getReadableDatabase();
        ArrayList<MessageItem> list = new ArrayList<MessageItem>();
        Cursor cursor = db.query(DatabaseHelper.LastChatRecord,
                new String[]{"SenderID", "Title", "IsGroup", "LastWord","UnReadCount", "Time"},
                null, null, "Title", null, "Time desc");
        while (cursor.moveToNext()) {
            MessageItem item = new MessageItem();
            item.senderID = (cursor.getString(cursor.getColumnIndex("SenderID")));
//            item.iconRes = cursor.getInt(cursor.getColumnIndex("IconRes"));
            item.title = cursor.getString(cursor.getColumnIndex("Title"));
            item.lastWord = cursor.getString(cursor.getColumnIndex("LastWord"));
            item.time = new Date(cursor.getLong(cursor.getColumnIndex("Time")));
            item.isNewMsg = cursor.getInt(cursor.getColumnIndex("UnReadCount")) > 0;
            item.unReadCount =cursor.getInt(cursor.getColumnIndex("UnReadCount"));
            item.isGroup = cursor.getInt(cursor.getColumnIndex("IsGroup")) == 1;
            list.add(item);
        }

        cursor.close();//关闭结果集
        db.close();//关闭数据库对象

        return list;
    }

    public MessageItem GetOneMessageItem(String senderID)
    {
        SQLiteDatabase db = DatabaseHelper.getInstance().getReadableDatabase();
        MessageItem item=null;
        Cursor cursor = db.query(DatabaseHelper.LastChatRecord,
                new String[]{"SenderID", "Title", "IsGroup", "LastWord","UnReadCount", "Time"},
                "SenderID=?", new String[]{senderID}, "Title", null, "Time desc");
        if(cursor.moveToNext())
        {
            item = new MessageItem();
            item.senderID = (cursor.getString(cursor.getColumnIndex("SenderID")));
//            item.iconRes = cursor.getInt(cursor.getColumnIndex("IconRes"));
            item.title = cursor.getString(cursor.getColumnIndex("Title"));
            item.lastWord = cursor.getString(cursor.getColumnIndex("LastWord"));
            item.time = new Date(cursor.getLong(cursor.getColumnIndex("Time")));
            item.isNewMsg = cursor.getInt(cursor.getColumnIndex("UnReadCount")) > 0;
            item.unReadCount=cursor.getInt(cursor.getColumnIndex("UnReadCount"));
            item.isGroup = cursor.getInt(cursor.getColumnIndex("IsGroup")) == 1;
        }
        return item;
    }

    public void update(MessageItem item) {
        SQLiteDatabase db =null;
        try{
        db = DatabaseHelper.getInstance().getWritableDatabase();
        ContentValues values = new ContentValues();
        values.put("Title", item.title);
        values.put("LastWord", item.lastWord);
//        if(item.iconRes!=0)
//        {
//            values.put("IconRes", item.iconRes);
//        }
        if(item.time!=null) {
            values.put("Time", item.time.getTime());
        }
        values.put("UnReadCount", item.unReadCount);
        db.update(DatabaseHelper.LastChatRecord, values, "SenderID=?", new String[]{item.senderID});
        }catch (Exception ex){
            ex.printStackTrace();
        }finally{
            if(db!=null){
                db.close();//关闭数据库对象
            }
        }
    }

    public String getLastWord(RichChatMessage content) {
        String contentStr = content.getText();
        if (content.getNonTextHashMap().size() > 0) {
            StringBuilder newContent = new StringBuilder(contentStr);
            int i = 0;

            for (Map.Entry<Integer, NonText> entry : content.getNonTextHashMap().entrySet()) {
                if (entry.getValue().getChatBoxElementType() == ChatBoxElemnetType.Emotion) {
                    newContent.insert(entry.getKey() + i, "[符号表情]");
                    i = i + 6;
                }
            }
            contentStr = newContent.toString();
        }

        if (content.getNonTextHashMap().size() > 0) {
            StringBuilder newContent = new StringBuilder(contentStr);
            int i = 0;
            for (Map.Entry<Integer, NonText> entry : content.getNonTextHashMap().entrySet()) {
                if (entry.getValue().getChatBoxElementType() == ChatBoxElemnetType.Image) {
                newContent.insert(entry.getKey() + i, "[图片]");
                i = i + 4;
            }}
            contentStr = newContent.toString();
        }

        if (contentStr.length() > 15) {
            contentStr = contentStr.substring(0, 14) + "...";
        }

        return contentStr;
    }

    private boolean existSender(String senderID) {
        SQLiteDatabase db = DatabaseHelper.getInstance().getReadableDatabase();
        Cursor cursor = db.query(DatabaseHelper.LastChatRecord,
                new String[]{"SenderID"}, "SenderID=?", new String[]{senderID}, null, null, null);
        return cursor.moveToNext();
    }

    public void delete(String senderID) {
        SQLiteDatabase db = DatabaseHelper.getInstance().getWritableDatabase();
        db.delete(DatabaseHelper.LastChatRecord, "SenderID=?", new String[]{senderID});
        db.close();//关闭数据库对象
        ClientGlobalCache.getInstance().removeNotReadMsg(senderID);
    }
}
